import { Plugin } from './Plugin';
import { ValidatorType, Validator } from '../validators/Validator';

export type OptionValidation<T> = {
  options: {
    [key in keyof T]: ValidatorType<T[key]>;
  };
};

export class PluginOption extends Plugin<Plugin.Console, OptionValidation<any>> {
  protected data: Record<string, Validator> = {};
  protected aliases: Record<string, undefined | string | string[]> = {};

  constructor() {
    super();

    this.use((ctx, next) => {
      const rawOptions = this.getOptions(ctx, this.aliases);
      ctx.options = {};

      for (const [key, validator] of Object.entries(this.data)) {
        ctx.options[key] = rawOptions[key];

        const msg = validator.validate(ctx.app.i18n, ctx.options, key);
        if (msg) {
          throw new Error(msg);
        }
      }

      return next();
    });
  }

  public setData(data: Record<string, Validator>) {
    this.data = data;
  }

  public setAlias(aliases: Record<string, undefined | string | string[]>) {
    this.aliases = aliases;
  }

  public getData() {
    return this.data;
  }

  public getAlias() {
    return this.aliases;
  }
}
